<template>
  <el-card>

    <!--  表格操作  -->
    <div class="select-div">
      <el-form :inline="true" style="height: 40px">

        <el-form-item>
          <el-input
              clearable
              v-model="condition.title"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入文章关键字"
              style="width:200px"
              @keyup.enter.native="searchComments"
          />
        </el-form-item>

        <el-form-item>
          <el-input
              clearable
              v-model="condition.username"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入用户关键字"
              style="width:200px"
              @keyup.enter.native="searchComments"
          />
        </el-form-item>

        <el-form-item>
          <el-select v-model="condition.isDelete" clearable placeholder="是否删除" size="small">
            <el-option label="未删除" :value="0"></el-option>
            <el-option label="已删除" :value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select v-model="condition.auditStatus" clearable placeholder="审核状态" size="small">
            <el-option label="审核正常" :value="0"></el-option>
            <el-option label="违规敏感" :value="1"></el-option>
            <el-option label="疑似敏感" :value="2"></el-option>
            <el-option label="被举报" :value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-button type="primary" size="small" icon="el-icon-search" style="margin-left:1rem"
                   @click="searchComments">
          搜索
        </el-button>

        <el-button type="danger" size="small" icon="el-icon-delete" @click="deleteCheck()"
                   :disabled="this.selection.length === 0">删除选中
        </el-button>

        <el-button type="primary" size="small" @click="downloadExcel">导出Excel</el-button>

      </el-form>
    </div>

    <!--  表格内容  -->
    <el-table :data="tableData"
              border
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="articleTitle" label="评论文章"></el-table-column>

      <el-table-column prop="username" label="评论用户"></el-table-column>

      <el-table-column prop="content" label="评论内容" show-overflow-tooltip></el-table-column>

      <el-table-column prop="likes" label="点赞量"></el-table-column>

      <el-table-column prop="createTime" label="评论时间"></el-table-column>
      
      <el-table-column prop="isDelete" label="是否删除">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isDelete === 0 ? 'success' : 'danger'">
            {{ scope.row.isDelete === 0 ? '未删除' : '已删除' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="auditStatus" label="审核状态">
        <template slot-scope="scope">
          <el-tag :type="getAuditStatusType(scope.row.auditStatus)">
            {{ getAuditStatusText(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="查看详情" placement="top-start">
            <el-button circle icon="el-icon-document" size="mini"
                       @click="showInfo(scope.row.id)"/>
          </el-tooltip>

          <el-tooltip effect="dark" content="删除" placement="top-start">
            <el-button circle icon="el-icon-delete" size="mini" placement="top-start" type="danger"
                       @click="deleteCheck(scope.row.id)"/>
          </el-tooltip>
          
          <el-tooltip effect="dark" content="审核" placement="top-start" v-if="scope.row.auditStatus === 2 || scope.row.auditStatus === 3">
            <el-button circle icon="el-icon-check" size="mini" type="warning"
                       @click="showAuditDialog(scope.row.id)"/>
          </el-tooltip>
        </template>
      </el-table-column>

    </el-table>

    <!--  分页  -->
    <pagination
        :total="total"
        :page_index="pageNum"
        @pageChange="pageChange"
    />

    <!--  详情弹出框  -->
    <el-dialog
        title="操作详情"
        :visible.sync="dialogInfo"
        width="40%"
        :before-close="handleCloseDialog">
      <el-form :model="commentFrom" ref="commentFrom" label-width="100px">

        <el-form-item label="文章标题" prop="articleTitle">
          <el-input v-model="commentFrom.articleTitle"></el-input>
        </el-form-item>

        <el-form-item label="评论用户" prop="username">
          <el-input v-model="commentFrom.username"></el-input>
        </el-form-item>

        <el-form-item label="请求数据" prop="content">
          <el-input type="textarea" v-model="commentFrom.content" :autosize="{ minRows: 2, maxRows: 6 }"
                    class="textarea"/>
        </el-form-item>

        <el-form-item label="评论时间" prop="creatTime">
          <el-input v-model="commentFrom.createTime"></el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    <!-- 审核弹出框 -->
    <el-dialog
        title="评论审核"
        :visible.sync="dialogAudit"
        width="40%"
        :before-close="handleCloseAuditDialog">
      <el-form :model="auditForm" ref="auditForm" label-width="100px">
        <el-form-item label="评论内容" prop="content">
          <el-input type="textarea" v-model="auditForm.content" :autosize="{ minRows: 2, maxRows: 6 }" readonly/>
        </el-form-item>
        
        <el-form-item label="审核结果" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus">
            <el-radio :label="0">审核通过</el-radio>
            <el-radio :label="1">违规敏感</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="审核备注" prop="auditRemark">
          <el-input type="textarea" v-model="auditForm.auditRemark" :autosize="{ minRows: 2, maxRows: 4 }"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAudit = false">取 消</el-button>
        <el-button type="primary" @click="submitAudit">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { commentApi } from '@/api';

export default {
  name: "Comment",
  data() {
    return {
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      selection: [],
      selectedNum: 0,
      commentFrom: {},
      dialogInfo: false,
      dialogAudit: false,
      auditForm: {
        id: null,
        content: '',
        auditStatus: 0,
        auditRemark: ''
      },
      condition: {
        title: null,
        username: null,
        isDelete: null,
        auditStatus: null
      }
    }
  },

  methods: {
    /**
     * 复选框事件
     * @param selection 选中数据数组
     */
    handleSelectionChange(selection) {
      this.selection = selection.map(item => item.id)
      this.selectedNum = selection.length
    },

    /**
     * 查询详情
     * @param id 数据id
     */
    showInfo(id) {
      this.commentFrom = this.tableData.find(obj => obj.id === id)
      this.dialogInfo = true;
    },

    /**
     * 分页回调函数
     * @param val
     */
    pageChange(val) {
      this.pageNum = val.pageNum;
      this.pageSize = val.pageSize;
      this.loadCommentList();
    },

    /**
     * input搜索触发事件
     */
    searchComments() {
      this.pageNum = 1;
      this.loadCommentList();
    },

    /**
     * 当用户通过点击关闭图标或遮罩关闭 Dialog 时起效的事件
     */
    handleCloseDialog() {
      //关闭Dialog时清空表单
      if (this.$refs.commentFrom !== undefined) this.$refs.commentFrom.resetFields();
      this.commentFrom = {};
      this.dialogInfo = false;
    },
    
    /**
     * 关闭审核弹窗
     */
    handleCloseAuditDialog() {
      if (this.$refs.auditForm !== undefined) this.$refs.auditForm.resetFields();
      this.auditForm = {
        id: null,
        content: '',
        auditStatus: 0,
        auditRemark: ''
      };
      this.dialogAudit = false;
    },

    /**
     * 获取审核状态对应的标签类型
     * @param status 审核状态
     * @returns {string} 标签类型
     */
    getAuditStatusType(status) {
      switch (status) {
        case 0: return 'success';
        case 1: return 'danger';
        case 2: return 'warning';
        case 3: return 'info';
        default: return 'info';
      }
    },
    
    /**
     * 获取审核状态对应的文本
     * @param status 审核状态
     * @returns {string} 状态文本
     */
    getAuditStatusText(status) {
      switch (status) {
        case 0: return '审核正常';
        case 1: return '违规敏感';
        case 2: return '疑似敏感';
        case 3: return '被举报';
        default: return '未知状态';
      }
    },
    
    /**
     * 显示审核弹窗
     * @param id 评论ID
     */
    showAuditDialog(id) {
      const comment = this.tableData.find(obj => obj.id === id);
      if (comment) {
        this.auditForm.id = comment.id;
        this.auditForm.content = comment.content;
        this.auditForm.auditStatus = 0;
        this.auditForm.auditRemark = '';
        this.dialogAudit = true;
      }
    },
    
    /**
     * 提交审核结果
     */
    submitAudit() {
      commentApi.auditComment(this.auditForm).then(response => {
        if (response.data.code === 20000) {
          this.$message({
            message: '审核成功！',
            type: 'success'
          });
          this.dialogAudit = false;
          this.loadCommentList();
        }
      }).catch(error => {
        console.error('审核评论失败', error);
      });
    },

    // Excel文件下载
    downloadExcel() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        articleTitle: this.condition.title,
        username: this.condition.username,
        isDelete: this.condition.isDelete,
        auditStatus: this.condition.auditStatus
      };
      
      commentApi.exportCommentExcel(params).then((response) => {
        const blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});
        const downloadElement = document.createElement('a');
        downloadElement.href = window.URL.createObjectURL(blob);
        downloadElement.download = 'comments.xlsx'; // 更改为更具描述性的文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载链接
        document.body.removeChild(downloadElement); // 下载完成后移除下载链接
      });
    },


    /**
     * 删除数据
     * @param id 数据id
     */
    deleteCheck(id) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning"
      }).then(() => {
        const ids = id == null ? this.selection : [id];
        commentApi.deleteComments(ids).then((response) => {
          if (response.data.code === 20000) {
            this.$message({
              message: '删除成功！',
              type: 'success'
            });
            this.loadCommentList();
          }
        });
      }).catch(() => {
        // 取消删除操作
      });
    },

    /**
     * 获取评论数据
     */
    loadCommentList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        articleTitle: this.condition.title,
        username: this.condition.username,
        isDelete: this.condition.isDelete,
        auditStatus: this.condition.auditStatus
      };
      
      commentApi.getCommentList(params).then(response => {
        if (response.data.code === 20000) {
          this.tableData = response.data.data.pagingList;
          this.total = response.data.data.count;
        }
      }).catch(error => {
        console.error('加载评论列表失败', error);
      });
    }
  },

  created() {
    this.loadCommentList();
  }
}
</script>

<style scoped>

</style>